package com.tnl.web.config.controller;

import java.util.List;




import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.biz.hunter.dao.CompanyDAO;
import com.biz.hunter.dao.HunterCompanyDAO;
import com.biz.hunter.dao.HunterDAO;
import com.biz.hunter.db.entity.HunterCompany;
import com.tnl.web.domain.AdminUser;
import com.tnl.web.dto.jqGridRequestObject;
import com.tnl.web.dto.jqGridResponseObject;
import com.tnl.web.entity.ErrorMsg;
import com.tnl.web.util.qualifiers.AuditIt;


@Controller
public class HunterCompanyController {
	private static final Logger logger = LoggerFactory.getLogger(HunterCompanyController.class);
	
	@Autowired
	private CompanyDAO companyDAO;
	@Autowired
	private HunterCompanyDAO hunterCompanyDAO;
	@Autowired
	private HunterDAO hunterDAO;
	@Autowired
	private Authentication authentication;

	// 猎头公司管理
	@AuditIt(module = "Company", action = "company_view", description = "Show the company index page")
	@RequestMapping(value = "admin/huntercompany/manage.page", method = RequestMethod.GET)
	public String hunterCompanyManagement(HttpServletRequest request, Model model) {
		
		HttpSession session = request.getSession();
		String userId = (String) session.getAttribute("UserId");

		logger.debug("userid is " + userId);
		if (!StringUtils.hasText(userId)) {

			logger.info("empty user id ,session is not initiallized.");
			return "admin/platformadminlogin";
		}

		AdminUser user = authentication.getCurrentUser();
		if (user == null) {
			logger.error("can not get the user info" + userId);
			return "admin/platformadminlogin";
		}
		
		return "admin/hunter/huntercompanylist";

	}

	// 显示编辑表单页面
	@AuditIt(module = "Company", action = "editCompany", description = "Show the company edit page")
	@RequestMapping(value = "admin/huntercompany/form.page", method = RequestMethod.GET)
	public String toEdit(HttpServletRequest request, Model model) {

		String companyid = request.getParameter("companyid");
		HunterCompany ht = null;
		if (StringUtils.hasText(companyid)) {
			ht = hunterCompanyDAO.getById(Integer.parseInt(companyid));
			model.addAttribute("company", ht);
		} else {
			return "admin/errorpage";
		}

		return "admin/hunter/huntercompanyeditform";
	}

	// 显示候选公司详细信息页面
	@RequestMapping(value = "admin/huntercompany/detail.page", method = RequestMethod.GET)
	public String employeeDetail(HttpServletRequest request, Model model) {

		String companyid = request.getParameter("companyid");
		
		HunterCompany ht = null;
		if (StringUtils.hasText(companyid)) {
			ht = hunterCompanyDAO.getById(Integer.parseInt(companyid));
			model.addAttribute("company", ht);
		} else {
			return "admin/errorpage";
		}
		
		return "admin/hunter/huntercompanydetail";
	}

	// 搜索数据
	@RequestMapping(value = "admin/huntercompany/search.do", method = RequestMethod.POST)
	public @ResponseBody jqGridResponseObject<HunterCompany> searchHunterCompany(jqGridRequestObject request, String sname, String sphone, Integer sstatus) {
		
		jqGridResponseObject<HunterCompany> msg = new jqGridResponseObject<HunterCompany>();
		
		long page = request.getPage();
		long pagesize = request.getRows();
		
		long totalrows = request.getTotalrows();
		long totalpages = 0;
		
		// 需要分页和计算总数
		if(totalrows == 0) {
			totalrows = hunterCompanyDAO.getCountOfAll(sname, sphone, sstatus);
		}
		totalpages = jqGridResponseObject.calTotalPage(totalrows, pagesize);
		
		// 起始位置
		long start = 0;
		start = (page-1) * pagesize;
		
		List<HunterCompany> list = hunterCompanyDAO.getAllWithLimit(sname, sphone,sstatus, start, pagesize);
		
		// 设置返回的数据
		msg.setPage(page);
		msg.setTotal(totalpages);
		msg.setRecords(totalrows);
		msg.setRows(list);
		
		return msg;
	}
	
	// 删除数据
	@AuditIt(module = "Company", action = "deleteCompany", description = "Delete company action")
	@RequestMapping(value = "admin/huntercompany/delete.do", method = RequestMethod.GET)
	public @ResponseBody ErrorMsg deleteHunter(HttpServletRequest request, Integer companyid) {
			
		ErrorMsg msg = new ErrorMsg();
			
		if (companyid == null) {
			logger.debug("companyid is null");
			msg.setErrorcode("-1");
			msg.setMsg("必须指定要删除数据");	
			return msg;
		}

		int result = hunterCompanyDAO.delete(String.valueOf(companyid));
		if (result == 1) {
			msg.setErrorcode("0");
			msg.setMsg("删除成功");
			return msg;
		}

		msg.setErrorcode("50001");
		msg.setMsg("删除失败");
		return msg;
	}

	// 更新数据
	@AuditIt(module = "Company", action = "editCompany", description = "Upadate company action")
	@RequestMapping(value = "admin/huntercompany/update.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg updateHunterCompany(HttpServletRequest request,  HunterCompany htcompany) {
		
		ErrorMsg msg = new ErrorMsg();
		
		if(htcompany == null) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定猎头公司信息");
			return msg;
		}
		if(htcompany.getId() <= 0) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定猎头公司信息");
			return msg;
		}
		
		HunterCompany ht = hunterCompanyDAO.getById(htcompany.getId());
		if(ht == null) {
			msg.setErrorcode("500101");
			msg.setMsg("没有该猎头");
			return msg;
		}
		
		ht.setName(htcompany.getName());
		ht.setAddress(htcompany.getAddress());
		ht.setApproved(1);
		ht.setContact(htcompany.getContact());
		ht.setLicenseCode(htcompany.getLicenseCode());
		ht.setOrgnizationCode(htcompany.getOrgnizationCode());

		int result = hunterCompanyDAO.update(ht);
		if (result == -1) {
			msg.setErrorcode("5001");
			msg.setMsg("更新数据失败");
			return msg;
		}
		msg.setErrorcode("0");
		msg.setMsg("数据更新成功");
		return msg;
	}

	// 批准公司
	@AuditIt(module = "Company", action = "approveCompany", description = "Approve company action")
	@RequestMapping(value = "admin/huntercompany/approve.do", method = RequestMethod.GET)
	public @ResponseBody ErrorMsg approveHunter(HttpServletRequest request, Integer companyid) {
			
		ErrorMsg msg = new ErrorMsg();
			
		if (companyid == null) {
			logger.debug("companyid is null");
			msg.setErrorcode("-1");
			msg.setMsg("必须指定要删除数据");	
			return msg;
		}
		HunterCompany ht = hunterCompanyDAO.getById(companyid);
		if(ht == null) {
			msg.setErrorcode("500101");
			msg.setMsg("没有该猎头");
			return msg;
		}
		ht.setApproved(1);

		int result = hunterCompanyDAO.update(ht);
		if (result == -1) {
			msg.setErrorcode("5001");
			msg.setMsg("更新数据失败");
			return msg;
		}

		msg.setErrorcode("0");
		msg.setMsg("数据更新成功");
		return msg;
	}

	/*
	@RequestMapping(value = "admin/huntercompany/toView.page", method = RequestMethod.GET)
	public HunterCompany getCompanyDetail(
			@RequestParam(value = "id", required = false, defaultValue = "0") Integer id) {
		HunterCompany company = hunterCompanyDAO.getById(id);
		return company;
	}

	@RequestMapping(value = "admin/huntercompany/getAllCompany.do", method = RequestMethod.GET)
	@ResponseBody
	public JqGridPage getAllCompany(JqGridPage page) {
		List<HunterCompany> list = hunterCompanyDAO.getALL();
		Page<HunterCompany> companies = new PageImpl<HunterCompany>(list,
				page.toPageable(), list.size());
		page = JqGridPage.valueOf(companies);
		return page;
	}

	

	@RequestMapping(value = "admin/huntercompany/create.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg createCompany(@RequestBody HunterCompany company) {
		logger.info("Start create HunterCompany.");
		ErrorMsg msg = new ErrorMsg();
		Date now = new Date();
		company.setCreateDate(now.getTime());
		int result = hunterCompanyDAO.save(company);
		if (result == -1) {
			logger.error("create company failed" + company);
			return null;
		}

		company.setId(result);
		return msg;
	}

	@RequestMapping(value = "admin/huntercompany/deactiveCompany.do", method = RequestMethod.DELETE)
	public @ResponseBody ErrorMsg deactiveCompany(@PathVariable("id") int Id) {
		logger.info("Start delete Company.");
		ErrorMsg msg = new ErrorMsg();
		HunterCompany company = hunterCompanyDAO.getById(Id);
		company.setApproved(-1);
		hunterCompanyDAO.update(company);
		return msg;
	}

	@RequestMapping(value = "admin/huntercompany/update.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg updateCompany(@RequestBody HunterCompany company) {
		logger.info("Start UPDATE HunterCompany.");
		ErrorMsg msg = new ErrorMsg();
		HunterCompany current = hunterCompanyDAO.getById(company.getId());
		convertCompany(company, current);
		hunterCompanyDAO.update(current);
		return msg;
	}

	private void convertCompany(HunterCompany srcCompany, HunterCompany destCompany) {
		destCompany.setContact(srcCompany.getContact());
		destCompany.setEmail(destCompany.getEmail());
		// ... TODO：

	}

	
	
	
	@RequestMapping(value = "admin/hunterCompany/create.do", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> createCompanyStep2(
			HttpServletRequest request, ModelMap model, CompanyDto dto) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		int result = -1;
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("openId");

		int hunterId = dto.getHunterid();
		if (hunterId == 0) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "invalid paramter in request for the hunerId");
			return returnMap;
		}
		Hunter hunter = hunterDAO.getById(hunterId);
		if (hunter == null) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg",
					"invalid paramter in request for the hunter id = "
							+ hunterId);
			return returnMap;
		}

		int companyId = persistentCompany(dto);
		if (companyId == -1) {
			returnMap.put("errorcode", "50105");
			returnMap.put("msg", " failed to persistent the hunter company ("
					+ dto.getCompanyname() + ")  Id =" + dto.getCompanyid());
			returnMap.put("data", companyId);
			return returnMap;
		}
		
		returnMap.put("errorcode", "200");
		returnMap.put("msg", "create company successfully");
		returnMap.put("data", companyId);
		return returnMap;
	}
	
	private int persistentCompany(CompanyDto dto) {
		int companyId = dto.getCompanyid();

		HunterCompany comp = hunterCompanyDAO.getById(companyId);
		if (comp != null) {// update
			// 认证通过，不再update
			if (comp.getApproved() == 1) {
				return companyId;
			}
			comp.setName(dto.getCompanyname());
			comp.setContact(dto.getCompanycontact());
			comp.setAddress(dto.getCompanyaddress());
			// comp.setEmail(dto.);
			comp.setPhone(dto.getCompanyphone());
			comp.setLicenseCode(dto.getBizcode());
			comp.setOrgnizationCode(dto.getOrgcode());
			//comp.setCreateId(dto.getHrid());
			int result = hunterCompanyDAO.update(comp);
			if (result == -1) {
				logger.error("failed to update hunter comapny" + companyId);
				return -1;
			}
			return companyId;
		}
		int huerntId = dto.getHunterid();
	
		// create new company
		comp = new HunterCompany();
		comp.setName(dto.getCompanyname());
		comp.setContact(dto.getCompanycontact());
		comp.setAddress(dto.getCompanyaddress());
		// comp.setEmail(dto.);
		comp.setPhone(dto.getCompanyphone());
		comp.setLicenseCode(dto.getBizcode());
		comp.setOrgnizationCode(dto.getOrgcode());
		comp.setApproved(0);
		Date now = new Date();
		comp.setCreateDate(now.getTime());
		//comp.setCreateId(dto.getHrid());
		int result = hunterCompanyDAO.save(comp);
		if (result == -1) {
			logger.error("failed to update hunter comapny" + comp.getName());
			return -1;
		}
		// companyId = comp.getId();

		return result;
	}
	*/
}